<template>
  <view class="container-main">
    <!-- 添加收货地址 -->
    <view class="addAddress" v-if="JSON.stringify(defaultAddress) == '{}'" @click="chooseUserAddress">
      <view class="text">
        请添加收货地址
      </view>
      <uni-icons type="forward" color="#9BA3AA"></uni-icons>
    </view>
    <!-- 展示收货地址处 -->
    <view class="deliveryAddress" v-else>
      <view class="address-item">
        <view class="left">
          <view class="name">
            {{defaultAddress.name}} {{defaultAddress.phone}}
          </view>
          <view class="address">
            {{defaultAddress.region}}{{defaultAddress.street}}
          </view>
        </view>
        <view class="right" @click="amendAddress">
          <uni-icons type="bars" size="30"></uni-icons>
        </view>
      </view>
    </view>
    <!-- 商品展示处 -->
    <view class="goodsList">
      <uni-swipe-action>
        <block v-for="(goods,index) in cart" :key="index">
          <uni-swipe-action-item :right-options="Newoptions" @click="deleteGoods(goods)">
            <view class="goods-item">
              <!-- 商品左侧图片区域 -->
              <view class="goods-item-left">
                <image :src="imgPrefixAddress + goods.goodsPreviews.split(',')[0]" class="goods-pic"></image>
              </view>
              <!-- 商品右侧信息区域 -->
              <view class="goods-item-right">
                <!-- 商品标题 -->
                <view class="goods-name">{{goods.goodsName}}</view>
                <view class="goods-specification">
                  {{goods.name}}
                </view>
                <view class="goods-info-box">
                  <!-- 商品价格 -->
                  <view class="goods-price">￥{{goods.retailValue}}</view>
                  <!-- 商品数量 -->
                  <uni-number-box :min="1" :value="goods.amount"
                    @change="numChangeHandler($event,goods.cartId)"></uni-number-box>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </block>
      </uni-swipe-action>
    </view>

    <!-- 到货时间 配送相关 -->
    <view class="distribution">
      <!-- 预计到货时间 -->
      <view class="time">
        <view class="time-left">
          <view class="big">
            预计到货时间
          </view>
          <view class="small">
            延期发货最多支持30天
          </view>
        </view>
        <view class="time-right">
          （请选择发货时间） 默认立即发货
          <uni-icons type="right"></uni-icons>
        </view>
      </view>
      <!-- 配送 -->
      <view class="peisong">
        <view class="left">
          配送
        </view>
        <view class="right">
          物流配送 快递{{defaultFreight}}元
        </view>
      </view>
    </view>
    <view class="oders">
      <view>
        <text>商品金额：</text>
        <text>¥{{totalPrice}}</text>
      </view>
      <view>
        <text>配送费：</text>
        <text>¥{{defaultFreight}}</text>
      </view>
      <view>
        <text>员工优惠：</text>
        <text>-¥0</text>
      </view>
    </view>
    <view class="jiesuan-button" @click="jiesuan">
      立即支付
    </view>
    <van-dialog id="van-dialog" />
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import Dialog from '@/wxcomponents/@vant/weapp/dialog/dialog';
  export default {
    data() {
      return {
        // 确认支付弹出层
        isShow: true,
        // 待支付总价
        allSumPrice: 0,
        // 默认total总价
        totalPrice: 0,
        // 默认运费
        defaultFreight: 0,
        // 需要购买的商品数量
        goodsNum: 1,
        // 传递过来的数据
        goodsInfo: {},
        // 默认地址展示
        defaultAddress: {},
        // 当前选择的收货地址
        choosedAddress: {},
        imgPrefixAddress: "https://bjlr-1316909348.cos.ap-chengdu.myqcloud.com",
        // pop弹出层开关
        show: false,
        Newoptions: [{
          text: '删除',
          style: {
            backgroundColor: '#B8C1CC'
          }
        }],
        cart: [],
        // 用户地址列表
        userAddress: []
      };
    },
    methods: {
      ...mapMutations('m_user', ['updateAddress']),
      otherFun(object) {
        if (object) {
          this.defaultAddress = object
        } else {}
      },
      // 结算
      jiesuan() {
        const that = this
        if (JSON.stringify(this.defaultAddress) == '{}') return uni.$showMsg('请选择收货地址')
        Dialog.confirm({
            message: `确认支付吗，包含运费价格：${that.totalPrice + that.defaultFreight}`,
          }).then(() => {
            const jiesuan = {
              openid: 'o7Qwa5JdbngEey8Ls1xGCrKAVsrk',
              order: {
                amountS: 999,
                freight: 1,
                paymentAmountS: 1000

              },
              orders: [{
                goodsId: 33,
                sonId: 22,
                number: 1,
                salesPrice: 999,
                consigneeName: '老师的',
                consigneePhone: '13712319531',
                consigneeRegion: '四川省成都市武侯区',
                consigneeLocation: '幸福街道小区'
              }]
            };
            this.ceshi() //获取证书
            this.jiesuanBuy(jiesuan) // 给后端发订单信息
          })
          .catch(() => {
            return uni.$showMsg('您取消了支付')
          });
      },
      // 获取证书
      async ceshi() {
        const res = await uni.$http.get('/flow/order/getMchSerialNo')
      },
      // 立即购买
      async jiesuanBuy(data) {
        const res = await uni.$http.post('/flow/checkout', data)
        if (res.data.code !== 200) return uni.$showMsg('请求失败')
        // 发起微信支付
        const payObj = {
          timeStamp: res.data.data.timeStamp + '',
          nonceStr: res.data.data.nonceStr + '',
          package: res.data.data.package + '',
          paySign: res.data.data.paySign + '',
          signType: res.data.data.signType + ''
        }
        // 向微信发起支付
        this.wxpay(payObj)
      },
      // 微信支付
      async wxpay(payInfo) {

        await uni.requestPayment({
          nonceStr: payInfo.nonceStr,
          timeStamp: payInfo.timeStamp,
          package: payInfo.package,
          paySign: payInfo.paySign,
          signType: payInfo.signType,
          success() {
            // uni.$http.post('/flow/pay/callback', {
            //   // orderNumber: payInfo.orderNumber,
            //   timeStamp: payInfo.timeStamp + '',
            //   nonceStr: payInfo.nonceStr + '',
            //   package: payInfo.package + '',
            //   paySign: payInfo.paySign + '',
            //   signType: payInfo.signType + ''
            // })
            uni.$http.post('/flow/cart/payment', {
              cyclotron: '1',
              orderNumber: payInfo.orderNumber,
            })
            uni.switchTab({
              url: '/pages/my/my'
            })
          },
          fail() {
            uni.$http.post('/flow/pay/callback', {
              // orderNumber: payInfo.orderNumber,
              timeStamp: payInfo.timeStamp + '',
              nonceStr: payInfo.nonceStr + '',
              package: payInfo.package + '',
              paySign: payInfo.paySign + '',
              signType: payInfo.signType + ''
            })
            //  支付失败跳转到商品详情页
            console.log('取消了支付');
          }
        })
      },
      // 选择 收货地址
      chooseUserAddress() {
        uni.navigateTo({
          url: '/subpkg/buyNowAddressList/buyNowAddressList'
        })
      },
      //  修改收货地址
      amendAddress(addressData) {
        uni.navigateTo({
          url: '/subpkg/addressList/addressList'
        })
      },
      //删除商品
      async deleteGoods(goods) {
        const params = {
          cartId: goods.cartId
        }
        const res = await uni.$http.post('/flow/cart/remove', params)
        if (res.data.code !== 200) return uni.$showMsg('删除失败')
        this.getUserCarCount()
      },
      // updateBuyCarCount点击修改购物车数量
      async updateBuyCarCount(obj) {
        const res = await uni.$http.post('/flow/cart/quantitychange', obj)
        if (res.data.code !== 200) return uni.$showMsg('修改失败')
      },
      open() {},
      close() {
        this.show = false
      },
      // 获取用户购物车信息
      async getUserCarCount() {
        let res = await uni.$http.get('/flow/cart/list')
        this.cart = res.data.data
      },
      // 获取运费
      async getGoodsFreight(goodsId, addressId) {
        const res = await uni.$http.post('/main/freight', {
          goodsId: goodsId + '',
          addressId: addressId + ''
        })
        if (res.data.code !== 200) return uni.$showMsg('获取运费失败，请重试')
        this.defaultFreight = Math.floor(res.data.msg)
      },
      // 获取当前用户所有地址信息
      async getUserAddress() {
        const res = await uni.$http.get('/personalcenter/address')
        if (res.data.code !== 200) return uni.$showMsg('获取用户收货地址信息失败')
        if (res.data.data.find(item => {
            return item.defaults == '0'
          })) {
          this.defaultAddress = res.data.data.find(item => {
            return item.defaults == '0'
          })
        } else {
          this.defaultAddress = {}
        }
      },
    },
    onLoad(options) {
      let that = this
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('acceptDataFromOpenerPage', function(data) {
        that.goodsInfo = data
        that.totalPrice = data.goodsPrice
        that.allSumPrice = data.goodsPrice
      });
      //获取当前用户购物车数据
      this.getUserCarCount();
      // 获取当前用户默认地址信息
      this.getUserAddress();
    },
    onShow() {
      this.otherFun() // 获取navigiteBack传递过来的数据
      // 获取运费
      if (JSON.stringify(this.defaultAddress) == '{}') {
        this.getGoodsFreight(this.goodsInfo.goodsId, '')
      } else {
        this.getGoodsFreight(this.goodsInfo.goodsId, this.defaultAddress.addressId)
      }
    },
    computed: {
      ...mapState('m_user', ['address']),
    },
    watch: {
      goodsNum: {
        handler(newVal, oldVal) {
          this.totalPrice = newVal * this.goodsInfo.goodsPrice
        },
        immediate: true
      }
    },
  }
</script>

<style lang="scss">
  page {
    background-color: #F5F6F9;
  }

  .addAddress {
    margin-bottom: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 44px;
    background-color: #FFFFFF;
    padding: 0 16px;

    .text {
      font-size: 14px;
      color: #000000;
    }
  }

  // 商品item
  .goodsList {
    background-color: white;
    padding: 0 16px;
    margin-bottom: 20rpx;

    .goods-item {
      display: flex;
      padding: 10px 5px;
      border-bottom: 1px solid #f0f0f0;

      .goods-item-left {
        margin-right: 5px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .goods-pic {
          width: 100px;
          height: 100px;
          display: block;
        }
      }

      .goods-item-right {
        display: flex;
        flex: 1;
        flex-direction: column;
        justify-content: space-between;

        .goods-info-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .goods-name {
          font-size: 14px;
          color: #66737F;
        }

        .goods-specification {
          font-size: 10px;
          color: #8F9CA9;
        }

        .goods-price {
          font-size: 14px;
          color: #141414;
        }
      }
    }
  }

  .distribution {
    padding: 0 16px;
    background-color: white;

    .time {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30rpx;
      border-bottom: 1px solid #8F9CA9;
      height: 50px;


      .time-left {
        .big {
          font-size: 14px;
          color: #141414;
        }

        .small {
          font-size: 11px;
          color: #141414;
        }
      }

      .time-right {
        font-size: 14px;
        color: #141414;
        height: 10px;
        line-height: 10px;
      }
    }

    .peisong {
      margin-bottom: 30rpx;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #141414;
      border-bottom: 1px solid #8F9CA9;
      height: 45px;
      line-height: 45px;
      text-align: center;

      .left {}

      .right {}
    }

    .fapiao {
      margin-bottom: 30rpx;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #141414;
      height: 45px;
      line-height: 45px;
      text-align: center;

      .left {}

      .right {}
    }
  }

  .oders {
    padding: 0 16px;
    background-color: white;

    view {
      display: flex;
      justify-content: space-between;
      color: #141414;
      font-size: 14px;
      height: 34px;
      line-height: 34px;
      margin-bottom: 10rpx;
    }
  }

  .jiesuan {
    display: flex;
    justify-content: center;

    view {
      background-color: #000000;
      width: 325px;
      height: 36px;
      color: white;
      border-radius: 14px;
      line-height: 36px;
      text-align: center;
    }
  }

  // .container-main {
  //   padding-bottom: 50px;

  // }

  .address-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    padding: 10px;

    .left {
      width: 240px;

      .name {
        font-size: 18px;
        color: #000000;
        margin-bottom: 20rpx;
      }

      .address {
        font-size: 14px;
        color: #8F9CA9;
        word-wrap: break-word;
      }
    }
  }

  .jiesuan-button {
    width: 200px;
    height: 50px;
    margin: 30px auto;
    text-align: center;
    line-height: 50px;
    background-color: #000000;
    color: white;
    border-radius: 30px;
  }
</style>